<template>
  <div
    class="page-common-layout"
    :class="tableUID && 'component-use'"
    :key="id"
  >
    <div class="page-common-content">
      <tool-bar
        @search="$refs.table.refresh(true)"
        @reset="resetSearch"
        class="form-view-tool-bar-container"
      >
        <!-- 批量操作按钮 例如：新增、删除等 -->
        <template
          v-if="formType !== 'viewData' && isShowToolForm"
          slot="toolBtn"
          slot-scope="scope"
        >
          <span v-for="(item, index) in topButtonList" :key="index">
            <template v-if="item.permissionId">
              <a-button
                v-if="item.checked && item.btnType != 'search'"
                :class="item.btnStyle"
                :icon="item.icon"
                @click="handleBtnEvent(item, $refs.table.rows)"
                v-action="item.permissionId"
                >{{ item.name }}</a-button
              >
              <combined-query
                v-if="item.checked && item.btnType == 'search'"
                v-action="item.permissionId"
                :columns="columns"
                @refresh="
                  (e) => {
                    (queryParam.advanceFilter = e), $refs.table.refresh(true);
                  }
                "
              />
            </template>
            <template v-else>
              <a-button
                v-if="item.checked && item.btnType != 'search'"
                :class="item.btnStyle"
                :icon="item.icon"
                @click="handleBtnEvent(item, $refs.table.rows)"
                >{{ item.name }}</a-button
              >
              <combined-query
                v-if="item.checked && item.btnType == 'search'"
                :columns="columns"
                @refresh="
                  (e) => {
                    (queryParam.advanceFilter = e), $refs.table.refresh(true);
                  }
                "
              />
            </template>
          </span>
          <a-icon
            type="setting"
            @click="columnSortVisible = true"
            style="float: right; margin: 9px 5px 0 0;"
          />
        </template>
        <!-- 搜索条件区域 -->
        <template slot="toolForm" v-if="searchData.list.length && isShowQuery">
          <a-form-item v-if="searchData.queryType === 'mergeQuery'">
            <a-input
              v-model="queryParam.mergeQuery"
              placeholder="请输入要搜索的条件"
            />
          </a-form-item>
          <template
            v-else-if="
              searchData.queryType === 'selectQuery' &&
                searchData.upperLimit <= searchData.list.length
            "
          >
            <a-form-item>
              <a-select allowClear style="width: 150px;" v-model="selectFiled">
                <a-select-option
                  v-for="(item, index) in searchData.list"
                  :key="item.filed"
                >
                  {{ item.filedName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-input
                v-model="queryParam[selectFiled]"
                placeholder="请输入要搜索的条件"
              />
            </a-form-item>
          </template>
          <a-form-item
            v-else
            v-for="(item, index) in searchData.list"
            :key="index"
          >
            <!-- 项目标段 -->
            <template v-if="item.filedType === 'projectBlock'">
              <projectBlock v-model="projectBlockVal"></projectBlock>
            </template>
            <template v-else-if="item.filedType === 'date'">
              <template v-if="item.type === 'range'">
                <a-range-picker
                  v-model="rangeDate[item.filed]"
                  :showTime="item.showTime"
                  @change="
                    (dates, dateStrings) =>
                      rangeQueryChange(dateStrings, item.filed)
                  "
                />
              </template>
              <template v-else>
                <t-date
                  type="date"
                  :placeholder="item.filedName"
                  v-model="queryParam[item.filed]"
                />
              </template>
            </template>
            <template v-else-if="item.filedType === 'time'">
              <t-date
                style="width: 183px;"
                type="time"
                dateFormat="HH:mm:ss"
                :placeholder="item.filedName"
                v-model="queryParam[item.filed]"
              />
            </template>
            <template
              v-else-if="
                ~['select', 'checkbox', 'radio', 'treeSelect'].indexOf(
                  item.filedType
                )
              "
            >
              <select-search
                :searchItem="item"
                :formJsonData="formJsonData"
                :type="item.filedType"
                v-model="queryParam[item.filed]"
              ></select-search>
            </template>
            <template v-else-if="item.filedType === 'userPop'">
              <personnel-popup
                style="width: 180px;"
                v-model="queryParam[item.filed]"
                :placeholder="item.filedName"
              ></personnel-popup>
            </template>
            <template v-else-if="item.filedType === 'depart'">
              <depart-popup
                style="width: 180px;"
                v-model="queryParam[item.filed]"
                :placeholder="item.filedName"
              ></depart-popup>
            </template>
            <template v-else>
              <a-input
                v-model="queryParam[item.filed]"
                :placeholder="item.filedName"
              />
            </template>
          </a-form-item>
        </template>
      </tool-bar>
      <!-- 表格 -->
      <template v-if="columnSuccess">
        <!-- 【普通】树形表格 -->
        <tree-grid
          v-if="formType == 'treeForm'"
          ref="normalTreeTable"
          :columns="columns"
          rowKey="uuid"
          :url="treeForm.normal.url"
          :parameter="treeForm.normal.parameter"
        >
          <template slot="renderAction" slot-scope="{ text, record }">
            <span v-for="(item, index) in lineButtonList" :key="index">
              <template v-if="item.permissionId">
                <a
                  style="margin-right: 5px"
                  :class="{ 'action-delete': item.name == '删除' }"
                  v-if="item.checked"
                  @click="handleTreeBtnEvent(item, record, 'normalTreeTable')"
                  v-action="item.permissionId"
                  >{{ item.name }}</a
                >
              </template>
              <template v-else>
                <a
                  style="margin-right: 5px"
                  :class="{ 'action-delete': item.name == '删除' }"
                  v-if="item.checked"
                  @click="handleTreeBtnEvent(item, record, 'normalTreeTable')"
                  >{{ item.name }}</a
                >
              </template>
            </span>
          </template>
        </tree-grid>

        <!-- 普通表格 -->
        <DataGrid
          v-else
          ref="table"
          :tableUuid="tableUuid"
          :scopedSlotsKeys="scopedSlotsKeys"
          :columns="columns"
          :url="url"
          :queryParam="queryParam"
          rowKey="uuid"
          :scroll="scroll"
          :pageSize="showPageSize"
          :showPagination="showPage"
          :showRowSelect="topButtonList.length > 0 ? true : false"
        >
          <template
            :slot="item"
            slot-scope="{ text, record }"
            v-for="(item, index) in switchSlotName"
          >
            <a-switch :checked="text == 'true' ? true : false" disabled />
          </template>
          <template slot="renderAction" slot-scope="{ text, record }">
            <span v-for="(item, index) in lineButtonList" :key="index">
              <template v-if="item.permissionId">
                <a
                  style="margin-right: 5px"
                  :class="{ 'action-delete': item.name == '删除' }"
                  v-if="item.checked"
                  @click="handleBtnEvent(item, record, 'inline')"
                  v-action="item.permissionId"
                  >{{ item.name }}</a
                >
              </template>
              <template v-else>
                <a-tooltip v-if="item.iconCls">
                  <template slot="title">
                    {{ item.name }}
                  </template>
                  <icon-font
                    :style="{
                      marginRight: '5px',
                      color: item.iconColor || '#1890ff',
                      fontSize: '18px',
                    }"
                    :type="'icon-' + item.iconCls"
                    @click="handleBtnEvent(item, record, 'inline')"
                  ></icon-font>
                </a-tooltip>

                <a
                  style="margin-right: 5px"
                  :class="{ 'action-delete': item.name == '删除' }"
                  v-else-if="item.checked"
                  @click="handleBtnEvent(item, record, 'inline')"
                  >{{ item.name }}</a
                >
              </template>
            </span>
          </template>
        </DataGrid>
      </template>

      <edit-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :url="url"
        :requestMethod="requestMethod"
        :tableDataType="tableDataType"
        @cancel="handleCancel()"
        @ok="handleOk()"
        :customFooter="modalFooter"
      />

      <form-view
        ref="formViewModal"
        :visible="formViewVisible"
        @ok="() => (formViewVisible = false)"
        @cancel="() => (formViewVisible = false)"
      >
      </form-view>

      <column-sort
        v-if="columns.length > 0"
        :visible="columnSortVisible"
        :columns="columns"
        @ok="columnSortVisible = false"
        @cancel="columnSortVisible = false"
      >
      </column-sort>
    </div>
    <!-- 图片预览弹窗 -->
    <previewImage
      :imgSrc="imgPreview"
      :visible.sync="imgVisible"
    ></previewImage>

    <!-- 附件预览弹窗 -->
    <previewModal
      :visible.sync="previewVisible"
      :loading="previewLoading"
      ref="previewModal"
    ></previewModal>

    <!-- 文件列表弹窗 -->
    <a-modal
      title="附件列表"
      width="600px"
      wrapClassName="custom-fileList-modal"
      :visible="fileListVisible"
      :destroyOnClose="true"
      :footer="null"
      @cancel="fileListVisible = false"
    >
      <div class="fileList-modal-container">
        <div
          class="file-item"
          v-for="(item, index) in fileListDataSource"
          :key="index"
        >
          <div class="icon" :class="getFileType(item.name)"></div>
          <div class="name" @click="previewFile(item)">
            {{ item.name }}
          </div>
          <div class="downLoad-btn" @click="downloadFile(item)">
            <a-icon type="download" />
          </div>
        </div>
      </div>
    </a-modal>

    <!--	新增编辑【树形表格】	 -->
    <edit-tree-form
      type="1"
      ref="masterModal"
      :visible="treeForm.editorVisible"
      :loading="treeForm.loading"
      :model="treeForm.masterMdl"
      @cancel="handleCancel()"
      @ok="handleOk()"
    />

    <!-- 模板导入 custom-fileList-modal-->
    <a-modal
      title="模板导入"
      width="600px"
      wrapClassName="custom-templateImport-modal"
      :visible="templateImport.visible"
      :destroyOnClose="true"
      @cancel="handleCloseTemplateImport()"
      @ok="handleOkTemplateImport()"
    >
      <div class="templateImport-modal-container">
        <a-form-model
          ref="ruleForm"
          :model="templateImport"
          :rules="templateImport.rules"
          :label-col="templateImport.labelCol"
          :wrapper-col="templateImport.wrapperCol"
        >
          <a-form-model-item ref="file" label="选择模板" prop="file">
            <a-upload-dragger
              :fileList="templateImport.fileList"
              name="file"
              :multiple="false"
              accept=".xls,.xlsx"
              :beforeUpload="handleTemplateBeforeUpload"
              :remove="removeTemplateImportFile"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">
                单击或拖动文件到此区域进行上传
              </p>
              <p class="ant-upload-hint">
                仅支持.xls、xlsx、.xlsm格式文件
              </p>
            </a-upload-dragger>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
    <!-- 流程图 -->
    <flowChat ref="flowChatForm"></flowChat>
    <!-- 审批记录 -->
    <comment-modal ref="commentModal"></comment-modal>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { DataGrid, TreeGrid } from "@/components";
import { treeGridMixin } from "@/mixins/treeGridMixin";
import { dataGridMixin } from "@/mixins/dataGridMixin";
import editForm from "./edit";
import formView from "./formView.vue";
import CombinedQuery from "@/components/TopVUI/custom/CombinedQuery";
import selectSearch from "../formPreview/selectSearch.vue";
import {
  objToParam,
  flatTreeData,
  downLoadFileByArraybuffer,
} from "@/utils/util";
import { columnsFilter } from "@/utils/columnsFilter"; // 表头权限过滤
import { PersonnelPopup, DepartPopup, projectBlock } from "@/components";
import previewImage from "@/components/TopVUI/custom/previewImage";
import previewModal from "@/pages/document/minio/previewModal";
import flowChat from "@/pages/workflow/apiFlowableTask/myMission/flowChat.vue";
import commentModal from "@/pages/workflow/oaLeave/comment.vue";
import { pdfStreamHandeler } from "@/services/common";
import { getToken } from "@/utils/TopVUI";
import editTreeForm from "@/pages/system/sysSample/modal/treeEdit";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
import { axios } from "@/utils/request";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
export default {
  name: "TableList",
  mixins: [dataGridMixin, treeGridMixin],
  components: {
    DataGrid,
    editForm,
    CombinedQuery,
    formView,
    selectSearch,
    PersonnelPopup,
    DepartPopup,
    previewImage,
    previewModal,
    TreeGrid,
    editTreeForm,
    IconFont,
    projectBlock,
    flowChat,
    commentModal,
  },
  provide() {
    // 使用函数的形式，可以访问到 `this`
    return {
      sameValue: false,
      extraParamsValue: () => this.extraParams,
    };
  },
  props: {
    //是否展示顶部查询区域
    isShowQuery: {
      type: Boolean,
      default: true,
    },
    //是否展示顶部操作按钮
    isShowToolForm: {
      type: Boolean,
      default: true,
    },
    //表单id
    tableUID: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      extraParams: {},
      scopedSlotsKeys: [],
      //模板导入弹窗
      templateImport: {
        visible: false,
        name: "",
        rules: {
          file: {
            required: true,
            message: "请选择您要导入的模板！",
            trigger: "change",
          },
        },
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
        file: null,
        options: {},
        fileList: [],
      },
      projectBlockVal: {},
      //树形表格
      treeForm: {
        //
        editorVisible: false,
        loading: false,
        masterMdl: null,
        //普通
        normal: {
          parameter: {
            father: {
              levelId: 1,
            },
            children: {},
          },
          url: {
            fathersUrl: "/system/exampleSingleTreegrid/getListByLevelId",
            expandUrl: "/system/exampleSingleTreegrid/getListByPid",
            masterUpdate: "/system/exampleSingleTreegrid/update",
            masterDelete: "/system/exampleSingleTreegrid/deleteBatch",
            masterSaveRoot: "/system/exampleSingleTreegrid/save",
            masterSave: "/system/exampleSingleTreegrid/save",
          },
        },
      },
      //
      fileListDataSource: [],
      fileListVisible: false,
      //图片预览弹窗
      imgVisible: false,
      imgPreview: "",
      //
      //附件预览弹窗
      previewVisible: false,
      previewLoading: false,
      id: `${new Date().getTime()}-${Math.floor(Math.random() * 10)}`,
      visible: false,
      formViewVisible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        listDataType: "web",
      },
      selectedRowKeys: [],
      selectedRows: [],
      rows: "", //选中行数据
      columns: [
        {
          title: "#",
          align: "center",
          width: 50,
          scopedSlots: {
            customRender: "serial",
          },
          fixed: "left",
        },
      ],
      url: {
        getPageSet: "/form/formDatabase/formGetPageSet",
        save: "/form/formDatabase/formSave",
        update: "/form/formDatabase/formUpdate",
        deleteBatch: "/form/formDatabase/formDelete",
      },
      toolbarTableHeight: 0,
      antbar: 0,
      antcontent: 0,
      pageClientHeight: 0, //使用固定的页面布局时的页面高度
      toolbarHeight: 0, //有表格操作按钮时的按钮高度
      paginationtHeight: 34, //分页组件的高度
      tableUuid: this.tableUID || this.$route.meta.tableUuid,
      formName: this.$route.meta.formName,
      dataSource: [],
      scroll: { y: false },
      topButtonList: [],
      lineButtonList: [],
      searchData: {
        list: [],
      },
      showPage: true,
      showPageSize: 20,
      formJsonData: "",
      interface: null,
      requestMethod: "get",
      selectFiled: "",
      tableDataType: "", // 表数据类型，是自动生成还是选择表
      iconData: [
        {
          key: "info",
          type: "info-circle",
          twoToneColor: "#1890ff",
        },
        {
          key: "success",
          type: "check-circle",
          twoToneColor: "#52c41a",
        },
        {
          key: "error",
          type: "close-circle",
          twoToneColor: "#f5222d",
        },
        {
          key: "warning",
          type: "exclamation-circle",
          twoToneColor: "#faad14",
        },
        {
          key: "confirm",
          type: "question-circle",
          twoToneColor: "#faad14",
        },
      ],
      drawingList: {},
      switchSlotName: [],
      rangeDate: [],
      columnSuccess: false,
      formType: "",
      interfaceUuid: "",
      columnSortVisible: false,
      //表单footer
      modalFooter: {},
      detailForm: "",
    };
  },
  watch: {
    projectBlockVal: {
      handler(val) {
        let { org_code, pro_code } = val;
        this.queryParam.pro_code = pro_code;
        this.queryParam.org_code = org_code;
      },
    },
    $route: function(newRoute, from) {
      // this.id = `${new Date().getTime()}-${Math.floor(Math.random() * 10)}`
      this.queryParam.uuid = this.tableUID || newRoute.meta.tableUuid;
      this.loadDataJson(newRoute.meta.tableUuid);
      this.resizeHandler();
      this.initResizeEvent();
    },
    selectFiled: {
      handler: function(newVal, oldVal) {
        delete this.queryParam[oldVal];
      },
    },
    isShowHeightY: {
      handler(val) {
        let { isShowToolForm, isShowQuery } = val;
        if (this.tableUID) {
          if (isShowToolForm && isShowQuery) {
            this.scroll = { y: "270px" };
          }
          if (!isShowToolForm && !isShowQuery) {
            this.scroll = { y: "400px" };
          }
          if (!isShowToolForm && isShowQuery) {
            this.scroll = { y: "350px" };
          }
          if (!isShowQuery && isShowToolForm) {
            this.scroll = { y: "350px" };
          }
        } else {
          this.scroll = {};
        }
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(["userInfo", "configData"]),
    ...mapGetters("setting", ["menuData"]),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      };
    },
    // 表格竖向滚动条设置  这里是根据每页数据条数大于等于20的时候出现滚动条

    tableHeight() {
      let height = "";
      if (!this.toolbarHeight) {
        height = `calc(100% - 40px)`;
      } else {
        height = `calc(100% - ${this.toolbarHeight}px - 40px)`;
      }
      return height;
    },
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    isShowHeightY() {
      let { isShowToolForm, isShowQuery } = this;
      return {
        isShowToolForm,
        isShowQuery,
      };
    },
  },
  // 组件销毁时移除监听事件
  beforeDestroy() {
    this.destroyResizeEvent();
  },
  mounted() {
    // this.loadDataJson(getQueryString("tableName"));
    this.queryParam.uuid = this.tableUID || this.$route.meta.tableUuid;
    this.loadDataJson(this.tableUuid);
    this.resizeHandler();
    this.initResizeEvent();
    //
    // if (this.tableUID) {
    //   this.scroll = { y: false };
    // } else {
    //   this.scroll = {};
    // }
  },
  methods: {
    //下载附件
    downloadFile(item = {}) {
      let { url, name } = item;
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", name);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    //关闭弹窗
    handleCancel() {
      this.visible = false;
    },

    resizeHandler() {
      // 获取页面内容的高度
      this.pageClientHeight = document.getElementsByClassName(
        "page-common-content"
      )[0]?.clientHeight;
    },
    // 获取数据
    loadDataJson(e) {
      this.columns = [];
      this.tableUuid = e;
      this.$post("/form/formBasicConfigure/getDetailByUuid", {
        uuid: this.tableUuid,
      }).then(async (res) => {
        this.detailForm = res.formDesign.designJson;
        this.formJsonData = res.formDesign.designJson;
        this.drawingList = JSON.parse(res.formList.webListJson);
        // this.tableDataType = res.formDatabase.type || 'viewData';
        this.tableDataType = res.formDatabase?.type || "";
        this.formType = res.formBasicConfigure.type;
        this.interfaceUuid = res.formBasicConfigure.interfaceUuid;
        if (this.formType !== "viewData") {
          this.tableDataType = res.formDatabase.type;
          this.url.getPageSet = "/form/formDatabase/formGetPageSet";
        } else {
          this.url.getPageSet =
            "/system/sysInterfaceManagement/formViewDataGetPageSet";
          this.queryParam.uuid = this.interfaceUuid;
        }
        this.switchSlotName = [];
        this.drawingList.listData.forEach((item, index) => {
          if (item.filedType === "switch") {
            this.switchSlotName.push("switch" + index);
            this.columns.push({
              title: item.filedName,
              dataIndex: item.filed,
              align: item.align,
              width: item.width,
              fixed: item.fixed,
              sorter: item.sort,
              PermissionCode: item.PermissionCode, // 表头权限标识
              scopedSlots: { customRender: "switch" + index },
            });
          } else {
            this.columns.push({
              title: item.filedName,
              dataIndex: item.filed,
              align: item.align,
              width: item.width,
              fixed: item.fixed,
              sorter: item.sort,
              PermissionCode: item.PermissionCode,
            });
          }
        });
        if (
          this.drawingList.listProData.lineButtonList.length &&
          this.formType !== "viewData"
        ) {
          this.columns.push({
            title: "操作",
            align: "center",
            dataIndex: "action",
            width: 240,
            scopedSlots: {
              customRender: "renderAction",
            },
            fixed: "right",
          });
        }
        // 表头权限过滤
        this.columns = await columnsFilter(this.columns);
        // 行内按钮数据
        this.lineButtonList = this.drawingList.listProData.lineButtonList;
        // 顶部按钮数据
        this.topButtonList = this.drawingList.listProData.topButtonList;
        // 查询数据
        this.searchData.list = this.drawingList.searchData.list;
        this.searchData.queryType = this.drawingList.searchData.queryType;
        this.searchData.upperLimit = this.drawingList.searchData.upperLimit;
        this.showPage = this.drawingList.listProData.showPage;
        this.showPageSize = this.drawingList.listProData.showPageSize;
        //进度分析表单
        if (this.tableUuid == "6E0B29C222E740DC94C5354B2C538C83") {
          this.scopedSlotsKeys = ["staus_code", "deviation"];
          this.columns.forEach((v) => {
            let { dataIndex } = v;
            if (dataIndex != "action") {
              if (this.scopedSlotsKeys.includes(dataIndex)) {
                v.scopedSlots = { customRender: dataIndex + "_text" };
              }
            }
          });
        } else {
          this.scopedSlotsKeys = [];
        }

        this.scroll.x = this.columns.length * 100;
        if (this.columns.length) {
          this.columnSuccess = true;
        }
        // if (this.columns.length > 10) {
        // 	this.columns.splice(11);
        // }
        //修改默认的相关接口地址为用户手动配置的接口地址
        let { addApiUrl, deleteApiUrl, detailApiUrl, listApiUrl } =
          JSON.parse(this.formJsonData)?.config ?? {};
        // 列表
        if (listApiUrl) {
          this.url.getPageSet = listApiUrl;
        }
        //新增
        if (addApiUrl) {
          this.url.save = addApiUrl;
        }
        //删除
        if (deleteApiUrl) {
          this.url.deleteBatch = deleteApiUrl;
        }
        this.id = `${new Date().getTime()}-${Math.floor(Math.random() * 10)}`;
      });
    },

    //导出
    handleExport(record) {
      let { fullPath } = this.$route;
      let flatData = flatTreeData(this.menuData, "children");
      let { title = "" } = flatData.find((v) => v.fullPath == fullPath) ?? {};
      //   let { selectedRowKeys } = this.$refs.table;
      //   if (selectedRowKeys.length == 0) {
      //     this.$message.warn("请勾选需要导出的数据");
      //     return;
      //   }
      let { $pagerData, queryParamObj } = this.$refs.table;
      let params = {
        ...queryParamObj,
      };
      this.$post("/form/formDatabase/formExport", params, {
        responseType: "arraybuffer",
      })
        .then((res) => {
          downLoadFileByArraybuffer(res, title ?? "下载文件");
        })
        .catch((_) => {
          this.$message.error("数据导出失败，请稍后重试！");
        });
    },

    // 新增
    handleAdd(record, options) {
      this.modalFooter = {};
      this.visible = true;
      this.$refs.createModal.title = "新增";
      this.$refs.createModal.loadData(this.tableUuid, "add", this.formJsonData);
    },
    // 编辑
    handleTableEdit(record) {
      this.rows = record;
      if (this.rows) {
        this.modalFooter = {};
        this.visible = true;
        this.$refs.createModal.title = "编辑";
        this.$refs.createModal.loading = true;
        //修改默认的相关接口地址为用户手动配置的接口地址
        let { editApiUrl, detailApiUrl } =
          JSON.parse(this.formJsonData)?.config ?? {};
        //编辑
        if (editApiUrl) {
          this.url.update = editApiUrl;
        }
        //详情
        let detailUrl = "/form/formDatabase/formGetDetail";
        if (detailApiUrl) {
          detailUrl = detailUrl;
        } else {
          detailUrl = "/form/formDatabase/formGetDetail";
        }
        this.$post(detailUrl, {
          uuid: record.uuid,
          formUuid: this.tableUuid,
        }).then((res) => {
          this.$refs.createModal.loadData(
            this.tableUuid,
            "edit",
            this.formJsonData,
            // this.dealData(false),
            res
          );
        });
      } else {
        this.$message.warn("请先选中需要修改的数据");
        return true;
      }
    },

    rowClassName(row) {
      return row.uuid === this.rows?.uuid ? "bg-bray" : ""; // 每条数据的唯一识别值
    },

    //附件预览
    handleFilePreview(record) {
      this.rows = record;
      let { tableUuid } = this;
      let { uuid } = record;
      this.$post("/form/formDatabase/formAttachmentPreview", {
        uuid: uuid,
        formUuid: tableUuid,
      }).then((res) => {
        if (res.length == 0) {
          this.$message.info("暂无附件！", 1.5);
          return;
        }
        //打开附件列表弹窗
        this.fileListVisible = true;
        this.fileListDataSource = res;
        return;

        if (res.length > 1) {
        } else {
          //直接预览
          this.fileListVisible = false;
          this.previewFile(res?.[0] ?? {});
        }
      });
    },

    //下载模板
    handleTemplateDownload(record, options) {
      this.rows = record;
      let { interfaceUuid, interfacePath } = options;
      if (!interfaceUuid) {
        this.$message.error("下载模板接口不存在！");
        return;
      }
      axios
        .get(interfacePath, {
          responseType: "arraybuffer",
        })
        .then((res) => {
          downLoadFileByArraybuffer(res, "模板文件");
        });
    },

    //上传文件之前钩子
    handleTemplateBeforeUpload(file) {
      this.templateImport.file = file;
      this.templateImport.fileList = [file];
      return false;
    },

    removeTemplateImportFile() {
      this.templateImport.file = null;
      this.templateImport.fileList = [];
    },

    //模板导入
    handleTemplateImport(record, options) {
      this.rows = record;
      let { tableUuid } = this;
      this.templateImport.visible = true;
      this.templateImport.options = options;
    },

    //模板导入-确认
    handleOkTemplateImport() {
      let { options, file } = this.templateImport;
      let { interfaceUuid, interfacePath } = options;
      if (!file) {
        this.$message.error("请选择您到导入的模板！");
        return;
      }
      if (!interfaceUuid) {
        this.$message.error("模板导入接口不存在！");
        return;
      }
      let formData = new FormData();
      formData.append("uploadFile", file);
      axios
        .post(interfacePath, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          let { sucess, errorMsg } = res;
          if (sucess == 0) {
            this.$notification.error({
              message: "导入失败",
              description: (h) => {
                return (
                  <div>
                    {errorMsg.map((v) => {
                      return <div style="margin-bottom:10px">{v}</div>;
                    })}
                  </div>
                );
              },
            });
          } else {
            this.handleCloseTemplateImport();
            //刷新表格数据
            this.$refs.table.refresh();
            this.$message.success(`成功导入${sucess}条数据！`, 1.5);
          }
        })
        .catch((_) => {})
        .finally((_) => {
          this.buttonLoading = false;
        });
    },

    //关闭模板导入弹窗
    handleCloseTemplateImport() {
      this.templateImport.visible = false;
      this.templateImport.file = null;
      this.templateImport.fileList = [];
    },

    //单文件预览
    previewFile(fileData = {}) {
      let { type, url, name } = fileData;
      //图片
      if (type == "image") {
        this.imgVisible = true;
        this.imgPreview = url;
      } else if (type == "video") {
        //视频
        this.previewVisible = true;
        this.previewLoading = true;
        pdfStreamHandeler("/document/minio/pdfStreamVideo", {
          fileuUrl: url,
        }).then((res) => {
          if (res.statusCode !== 300) {
            let binaryData = [];
            binaryData.push(res);
            const blob = new Blob(binaryData, {
              type: "application/video;charset-UTF-8",
            });
            const objectUrl = window.URL.createObjectURL(blob);
            // window.open("./statics/pdf/web/viewer.html?file=" + objectUrl);
            // // this.pdfUrl = objectUrl;
            this.$refs.previewModal.type = "video";
            this.$refs.previewModal.fileUrl = objectUrl;
            this.previewLoading = false;
            // this.visibleVideo = true;
          } else {
            this.$message.error(
              res.message ? res.message : "获取资源失败！",
              1.5
            );
            this.previewVisible = false;
            this.previewLoading = false;
          }
        });
      } else {
        //其他附件
        this.$refs.previewModal.type = "file";
        this.$refs.previewModal.fileUrl =
          this.kkFileView +
          "/onlinePreview?url=" +
          encodeURIComponent(Base64.encode(url)) +
          "&watermarkTxt=" +
          //水印内容
          encodeURIComponent("") +
          "&token=" +
          getToken();
        this.previewVisible = true;
      }
    },

    //判断文件格式
    getFileType(name = "") {
      let fileType = name.substring(name.lastIndexOf(".") + 1);
      return fileType.toLowerCase();
    },

    // 预览详情
    handleView(record) {
      this.rows = record;
      if (this.rows) {
        this.modalFooter = { footer: null };
        this.visible = true;
        this.$refs.createModal.title = "详情";
        this.$refs.createModal.loading = true;
        let { detailApiUrl } = JSON.parse(this.formJsonData)?.config ?? {};
        //详情
        let detailUrl = "/form/formDatabase/formGetDetail";
        if (detailApiUrl) {
          detailUrl = detailUrl;
        } else {
          detailUrl = "/form/formDatabase/formGetDetail";
        }
        this.$post(detailUrl, {
          uuid: this.rows.uuid,
          formUuid: this.tableUuid,
        }).then((res) => {
          this.$refs.createModal.loadData(
            this.tableUuid,
            "view",
            // this.formJsonData,
            this.dealData(true),
            res
          );
        });
      } else {
        this.$message.warn("请选中需要查看的数据");
        return true;
      }
    },

    //查看流程图
    handleviewFlowChart(record) {
      this.$post("/workflow/oaLeave/clickFlowChart", {
        uuid: record.uuid,
      }).then((res) => {
        if (res.statusCode != 300) {
          const jsonData = res;
          this.$refs.flowChatForm.loadData(
            jsonData,
            jsonData.lists.actDeModelId,
            jsonData.lists.actDeModelKey,
            jsonData.lists.actDeModelName,
            jsonData.lists.flowDesign,
            record
          );
        } else {
          this.$message.error(res.message);
        }
      });
    },

    //查看审批记录
    handleGetListComments(record) {
      this.$refs.commentModal.getCommentList(record.uuid);
    },

    dealData(disabled = false) {
      let dealData = JSON.parse(this.detailForm);
      let { list = [], config } = dealData;
      config.hideRequiredMark = true;
      list.forEach((v) => {
        let { columns = [], options } = v;
        if (options) {
          options.disabled = disabled;
        }
        columns.forEach((item) => {
          let { list = [] } = item;
          list.forEach((c) => {
            let { options } = c;
            options.disabled = disabled;
          });
        });
      });
      this.detailForm = JSON.stringify(dealData);
      return this.detailForm;
    },

    handleOk: function() {
      this.visible = false;
      this.$refs.table.refresh();
    },
    // 删除
    handleDelete(e, type) {
      const that = this;
      let uuids = "";
      if (that.$refs.table.selectedRowKeys.length === 0 && type != "inline") {
        that.$message.warn("请勾选需要删除的数据");
        return;
      } else {
        uuids =
          type === "inline"
            ? e.uuid
            : that.$refs.table.selectedRowKeys.toString();
      }
      that.$confirm({
        title: that.$ct("tips", "提示"),
        content: that.$ct(
          "deleteConfirmationPrompt",
          "确定删除该数据吗？删除之后不可恢复！"
        ),
        okText: that.$ct("confirm", "确定"),
        cancelText: that.$ct("cancel", "取消"),
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          // 在这里调用删除接口
          that
            .$post(that.url.deleteBatch, {
              uuid: uuids,
              formUuid: that.tableUuid,
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功");
                that.rows = "";
                that.$refs.table.selectedRowKeys = [];
                that.$refs.table.refresh();
              } else {
                that.$message.error("删除失败");
              }
            });
        },
        onCancel() {},
      });
    },
    resetSearch() {
      this.selectFiled = "";
      this.rangeDate = [];
      this.projectBlockVal = "{}";
      this.queryParam = {
        uuid:
          this.formType === "viewData" ? this.interfaceUuid : this.tableUuid,
        listDataType: "web",
      };
      this.$refs.table.refresh(true);
    },

    //普通表格
    handleBtnEvent(options, record, type) {
      this.requestMethod = options.requestMethod;
      this.interface = options.interfaceUuid
        ? "/system/sysInterfaceManagement/invokeInterface"
        : null; // 接口地址
      const interfaceUuid = options.interfaceUuid || null; // 接口管理uuid
      //   this.extraParams = record;
      if (options.btnType === "export") {
        //zhailei【导出】
        this.handleExport(record);
      } else if (options.btnType === "filePreview") {
        //zhailei【附件预览】
        this.handleFilePreview(record);
      } else if (options.btnType === "templateDownload") {
        //zhailei【模板下载】
        this.handleTemplateDownload(record, options);
      } else if (options.btnType === "templateImport") {
        //zhailei【模板导入】
        this.handleTemplateImport(record, options);
      } else if (options.btnType === "detail") {
        //zhailei【详情】
        this.handleView(record);
      } else if (options.btnType === "flowChart") {
        //zhailei【流程图】
        this.handleviewFlowChart(record, options);
      } else if (options.btnType === "approvalRecord") {
        //zhailei【审批记录】
        this.handleGetListComments(record, options);
      } else if (options.btnType === "add") {
        this.url.save = this.interface || this.url.save;
        this.handleAdd(record, options);
      } else if (options.btnType === "edit") {
        this.url.update = this.interface || this.url.update;
        this.mdl = record;
        this.handleTableEdit(record);
      } else if (options.btnType === "delete") {
        this.url.deleteBatch = this.interface || this.url.deleteBatch;
        this.handleDelete(record, type);
      } else if (options.btnType === "search") {
      } else if (options.newlyAdded) {
        let param;
        let that = this;
        if (options.tableRowKey === 2) {
          that.handleConfirm(that.interface, param, record, options);
        } else if (!record) {
          that.$message.warn("请选择需要操作的数据", 1.5);
        } else {
          const data = options.requestParam;
          if (data.length) {
            param = JSON.parse(data).reduce((obj, item) => {
              obj[item.paramsName] =
                record[item.paramsValue] || item.paramsValue;
              return obj;
            }, {});
          }
          param.uuid = interfaceUuid;
          // if(options.requestParam){
          // 	param = {}
          // 	let data = options.requestParam.split(",")
          // 	data.forEach(item => {
          // 			param[item.split(":")[0]] = record[item.split(":")[1]] || item.split(":")[1]
          // 	})
          // }
          if (options.showDialog) {
            let obj = that.iconData.filter(
              (item) => item.key === options.messageIcon
            )[0];
            obj.theme = "twoTone";
            that.$confirm({
              title: "操作提示",
              content: options.message || "确定要执行该操作吗？",
              okText: options.okText || "确定",
              okType: "danger",
              cancelText: options.cancelText || "取消",
              icon: () =>
                that.$createElement("a-icon", {
                  props: obj,
                }),
              onOk() {
                that.handleConfirm(that.interface, param, record, options);
              },
            });
          } else {
            let url = that.splicing(that.interface, param || record);
            that["$" + that.requestMethod](url, param || record).then((res) => {
              //   if (res.statusCode === 200) {
              //     that.$refs.table.refresh();
              //     that.$message.success(res.message || "操作成功", 1.5);
              //   } else {
              //     that.$message.error(res.message || "操作失败", 1.5);
              //   }
            });
          }
        }
      }
    },

    //树形表格
    handleTreeBtnEvent(options, record, refName) {
      let { url } = this.treeForm.normal;
      let { btnType } = options;
      switch (btnType) {
        //删除
        case "delete":
          this.handleSub(record, url, { tableRef: refName });
          break;

        //编辑
        case "edit":
          this.handleTableEdit(record);
          break;

        default:
          break;
      }
    },

    handleConfirm(url, param, record, options) {
      if (options.tableRowKey === 1) {
        let requestUrl = this.splicing(url, param || record);
        this["$" + this.requestMethod](requestUrl, param || record).then(
          (res) => {
            if (res.statusCode === 200) {
              this.$refs.table.refresh();
              this.$message.success(res.message || "操作成功", 1.5);
            } else {
              this.$message.error(res.message || "操作失败", 1.5);
            }
          }
        );
      } else if (options.tableRowKey === 2) {
        // this.handleAdd()
        this.$refs.formViewModal.plugs = [];
        this.$refs.formViewModal.plugs.push((resolve) =>
          require([`@/pages${options.formUrl}.vue`], resolve)
        );
        this.$refs.formViewModal.drawingList = record;
        this.$refs.formViewModal.saveUrl = options.formSaveUrl;
        this.$refs.formViewModal.title = options.name;
        this.formViewVisible = true;
      } else if (options.tableRowKey === 3) {
        let param = {
          ...record,
          modelKey: options.flowModelKey,
          businessTitle: options.businessTitle + "-" + this.userInfo.userName,
        };
        param.businessUuid = param.uuid;
        delete param.uuid;
        this.$post(
          "/workflow/apiFlowableProcessInstance/startProcessInstanceByKey",
          param
        ).then((res) => {
          if (res.status !== 300) {
            this.$message.success("流程启动成功！", 1.5);
          } else {
            this.$message.warn(res.message, 1.5);
          }
        });
      }
    },
    //监听resize
    initResizeEvent() {
      window.addEventListener("resize", this.resizeHandler, false);
    },
    //移除resize
    destroyResizeEvent() {
      window.removeEventListener("resize", this.resizeHandler);
    },
    splicing(url, pramar) {
      if (this.requestMethod === "get" && url.indexOf("?") > -1) {
        url = url + objToParam(pramar, "&") || "";
      } else if (this.requestMethod === "get" && url.indexOf("?") === -1) {
        url = url + objToParam(pramar);
      }
      return url;
    },
    rangeQueryChange(dateStrings, filed) {
      this.queryParam[filed] = JSON.stringify(dateStrings);
      this.rangeDate.push({
        [filed]: JSON.stringify(dateStrings),
      });
    },
  },
};
</script>

<style lang="less" scoped="scoped">
.page-common-layout {
  &.component-use {
    background: red;
    height: 100%;
  }
}

/deep/.ant-btn {
  margin-right: 10px !important;
}
/deep/.custom-fileList-modal {
  .ant-modal-body {
    padding: 0 !important;
    .fileList-modal-container {
      height: 350px;
      padding: 20px 40px;
      overflow: auto;
      .file-item {
        display: flex;
        align-items: center;
        font-size: 15px;
        position: relative;
        &:not(:last-child) {
          margin-bottom: 26px;
        }
        .icon {
          width: 24px;
          height: 28px;
          margin-right: 10px;
          &.pdf {
            background: url("~@/assets/img/fileIcon/pdf.png");
            background-size: 100% 100%;
          }
          &.doc,
          &.docx {
            background: url("~@/assets/img/fileIcon/doc.png");
            background-size: 100% 100%;
          }
          &.xls,
          &.xlsx {
            background: url("~@/assets/img/fileIcon/xls.png");
            background-size: 100% 100%;
          }
          &.ppt,
          &.pptx,
          &.pps {
            background: url("~@/assets/img/fileIcon/ppt.png");
            background-size: 100% 100%;
          }
          &.png,
          &.jpg,
          &.jpeg,
          &.bmp,
          &.gif {
            background: url("~@/assets/img/fileIcon/image.png");
            background-size: 100% 100%;
          }
          &.mp3,
          &.wav,
          &.mp4,
          &.flv,
          &.avi {
            background: url("~@/assets/img/fileIcon/video.png");
            background-size: 100% 100%;
          }
        }
        .name {
          cursor: pointer;
          color: #333;
          padding-right: 30px;
          &:hover {
            color: var(--antd-wave-shadow-color);
            text-decoration: underline;
          }
        }
        .downLoad-btn {
          color: var(--antd-wave-shadow-color);
          cursor: pointer;
          position: absolute;
          top: 50%;
          right: -10px;
          transform: translateY(-50%);
          .anticon {
            font-size: 20px;
          }
        }
      }
    }
  }
}

/deep/.custom-templateImport-modal {
  .ant-modal-body {
    .templateImport-modal-container {
    }
  }
}
</style>
